import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/config/ui_constant.dart';
import 'package:star_author/utils/common_util/date_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/rong_im/rong_im.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/widgets/button_widget.dart';
import 'package:star_author/widgets/cover_widget.dart';
import 'package:star_author/widgets/dialog/dialog_type.dart';
import 'package:star_author/widgets/dialog/sure_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../utils/event.dart';

class ConnectMicrophoneManagement extends StatefulWidget {
  bool isConnect;
  Function(bool result)? callBack;
  Function(int userId, String type)? userCallBack;
  bool user_in_live;

  ConnectMicrophoneManagement(
      {Key? key,
      this.isConnect: false,
      this.callBack,
      this.userCallBack,
      this.user_in_live: false})
      : super(key: key);

  @override
  State<ConnectMicrophoneManagement> createState() =>
      _ConnectMicrophoneManagementState();
}

class _ConnectMicrophoneManagementState
    extends State<ConnectMicrophoneManagement> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isConnect = widget.isConnect;
    Event.on("GetInitConnectCountInDialog", (arg) {
      init();
    });
    Event.on("changed_user_in_live", (arg) {
      widget.user_in_live = arg;
    });
    init();
  }

  @override
  void dispose() {
    super.dispose();
    Event.off('GetInitConnectCountInDialog');
  }

  init() {
    if (isConnect) {
      HttpUtil.commonRequest(
        Get.context!,
        '/api/v1/studios/${StreamConf.liveId}/user_studios',
      ).then((value) {
        setState(() {
          List _data = (value.data['data'] ?? []);
          data = _data.reversed.toList();
        });
      });
    }
  }

  List data = [];

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(
        minHeight: 192.w,
      ),
      width: Get.width,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16.w),
          topRight: Radius.circular(16.w),
        ),
      ),
      child: Stack(
        children: [
          Column(
            children: [
              Container(
                margin: EdgeInsets.only(top: 20.w, bottom: 20.w),
                alignment: Alignment.topCenter,
                child: Text(
                  "连麦管理",
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: UIConstant.color33,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              buildContent(),
            ],
          ),
          Positioned(
            child: GestureDetector(
              child: Container(
                child: RoucesUtil.getAssetsIcon('ic_close_gray', 14.w),
              ),
              onTap: () {
                Get.back();
              },
            ),
            right: 14.w,
            top: 14.w,
          )
        ],
      ),
      padding:
          EdgeInsets.only(bottom: MediaQuery.of(context).padding.bottom + 10.w),
    );
  }

  bool isConnect = false;

  buildContent() {
    if (isConnect) {
      return Column(
        children: [
          Container(
            constraints:
                BoxConstraints(maxHeight: Get.height * 0.4, minHeight: 150.w),
            child: Builder(
              builder: (context) {
                if (data.length == 0) {
                  return Container(
                    height: 150.w,
                    alignment: Alignment.center,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          'images/lt_common/no_data.png',
                          width: 125.w,
                          height: 80.w,
                        ),
                        Text(
                          "暂无等待连麦的用户",
                          style: TextStyle(
                              fontSize: 14.sp, color: Color(0xFF999999)),
                        ),
                      ],
                    ),
                  );
                } else {
                  return ListView.builder(
                    shrinkWrap: true,
                    itemBuilder: (context, index) {
                      DateTime? create_at = DateUtil.getDateTime(
                          data[index]['created_at'] ?? "",
                          isUtc: false);
                      int minute =
                          DateTime.now().difference(create_at!).inMinutes;
                      bool isMinute = true;
                      if (minute == 0) {
                        isMinute = false;
                        minute = DateTime.now().difference(create_at).inSeconds;
                      }
                      return Container(
                        width: Get.width,
                        padding: EdgeInsets.symmetric(
                            horizontal: 12.w, vertical: 7.w),
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(
                              color: Color(0xFFEEEEEE),
                              width: 1,
                            ),
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                buildCircleCover(
                                    size: 40,
                                    cover: data[index]['avatar'] ?? ""),
                                SizedBox(
                                  width: 10.w,
                                ),
                                Container(
                                  height: 40.w,
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      Row(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        children: [
                                          Container(
                                            child: Text(
                                              "${data[index]['nickname'] ?? ""}",
                                              style: TextStyle(
                                                fontSize: 14.sp,
                                                color: UIConstant.color33,
                                              ),
                                              maxLines: 1,
                                            ),
                                            constraints: BoxConstraints(
                                                maxWidth: Get.width * 0.4,
                                                minWidth: 100.w),
                                          ),
                                          SizedBox(
                                            width: 4.w,
                                          ),
                                          Image.asset(
                                            'images/lt_user/owner/level_${data[index]['normal_level'] ?? 0}.png',
                                            width: 22.w,
                                            height: 12.w,
                                            fit: BoxFit.cover,
                                          ),
                                          SizedBox(
                                            width: 8.w,
                                          ),
                                          Image.asset(
                                            'images/lt_user/level/level_${data[index]['bidder_level'] ?? 0}.png',
                                            width: 22.w,
                                            height: 12.w,
                                            fit: BoxFit.cover,
                                          ),
                                        ],
                                      ),
                                      data[index]['connect_at'] != null
                                          ? !widget.user_in_live
                                              ? Text(
                                                  "连接中...",
                                                  style: TextStyle(
                                                    fontSize: 12.sp,
                                                    color: UIConstant.color99,
                                                  ),
                                                )
                                              : Row(
                                                  children: [
                                                    Image.asset(
                                                      'images/video_loading_lt.gif',
                                                      width: 10.w,
                                                      height: 12.w,
                                                      color: Color(0xFFF04529),
                                                    ),
                                                    SizedBox(
                                                      width: 4.w,
                                                    ),
                                                    Text(
                                                      "正在连线",
                                                      style: TextStyle(
                                                        fontSize: 12.sp,
                                                        color:
                                                            UIConstant.color99,
                                                      ),
                                                    ),
                                                  ],
                                                )
                                          : Text(
                                              "${minute}${isMinute ? "分" : "秒"}钟前申请",
                                              style: TextStyle(
                                                fontSize: 12.sp,
                                                color: UIConstant.color99,
                                              ),
                                            ),
                                    ],
                                  ),
                                )
                              ],
                            ),
                            Builder(builder: (context) {
                              if (data[index]['connect_at'] != null) {
                                return ButtonWidget(
                                  child: '断开连接',
                                  type: ButtonType.bdNormal,
                                  width: 80,
                                  fontSize: 14,
                                  height: 28,
                                  onPressed: () async {
                                    DialogUtil.showMyDialog(
                                        dialogType: DialogType.AnchorDisconnect,
                                        rightButtonOnTap: () {
                                          HttpUtil.commonRequest(Get.context!,
                                              '/api/v1/studios/${StreamConf.liveId}/touch_user_studio',
                                              method: HttpUtil.MethodPut,
                                              data: {
                                                "user_id": data[index]['id'],
                                                "event": 'disconnect',
                                                "is_expired":
                                                    !widget.user_in_live,
                                              }).then((value) async {
                                            widget.userCallBack!(
                                                0, "disconnect");
                                            await RongUtil.operation(
                                                OperationKey
                                                    .close_connecting_mic,
                                                {
                                                  "user_id": data[index]['id'],
                                                  "nickname": data[index]
                                                          ['nickname'] ??
                                                      "",
                                                  "connect_type": "disconnect",
                                                });
                                            init();
                                          });
                                        });
                                  },
                                );
                              } else {
                                return ButtonWidget(
                                  child: '立即连线',
                                  type: ButtonType.bgOrange,
                                  width: 80,
                                  fontSize: 14,
                                  height: 28,
                                  onPressed: () async {
                                    join() async {
                                      HttpUtil.commonRequest(Get.context!,
                                          '/api/v1/studios/${StreamConf.liveId}/touch_user_studio',
                                          method: HttpUtil.MethodPut,
                                          data: {
                                            "user_id": data[index]['id'],
                                            "event": 'connect',
                                          }).then((value) async {
                                        await RongUtil.operation(
                                            OperationKey.connecting_mic, {
                                          "user_id": data[index]['id'],
                                          "connect_type": "connect",
                                          "nickname":
                                              data[index]['nickname'] ?? "",
                                        });
                                        widget.userCallBack!(
                                            data[index]['id'], "connect");
                                        init();
                                        Get.back();
                                      });
                                    }

                                    int indexWhere = data.indexWhere(
                                        (element) =>
                                            element['connect_at'] != null);
                                    if (indexWhere != -1) {
                                      //有人在连麦 需要弹框
                                      DialogUtil.showMyDialog(
                                        dialogType: DialogType
                                            .AnchorDisconnectWithUserConnect,
                                        rightButtonOnTap: () async {
                                          await HttpUtil.commonRequest(
                                              Get.context!,
                                              '/api/v1/studios/${StreamConf.liveId}/touch_user_studio',
                                              method: HttpUtil.MethodPut,
                                              data: {
                                                "user_id": data[indexWhere]
                                                    ['id'],
                                                "event": 'disconnect',
                                                "is_expired":
                                                    !widget.user_in_live,
                                              }).then((value) async {
                                            widget.userCallBack!(
                                                data[indexWhere]['id'],
                                                "disconnect");
                                            await RongUtil.operation(
                                                OperationKey
                                                    .close_connecting_mic,
                                                {
                                                  "user_id": data[indexWhere]
                                                      ['id'],
                                                  "nickname": data[index]
                                                          ['nickname'] ??
                                                      "",
                                                  "connect_type": "disconnect",
                                                });
                                            join();
                                          });
                                        },
                                      );
                                    } else {
                                      join();
                                    }
                                  },
                                );
                              }
                            })
                          ],
                        ),
                      );
                    },
                    itemCount: data.length,
                  );
                }
              },
            ),
          ),
          GestureDetector(
            child: Container(
              color: Color(0xFFEEEEEE),
              alignment: Alignment.center,
              width: Get.width,
              height: 48.w,
              child: Text(
                "关闭鉴宝",
                style: TextStyle(
                  fontSize: 16.sp,
                  color: UIConstant.color33,
                ),
              ),
            ),
            onTap: () {
              DialogUtil.showMyDialog(
                dialogType: DialogType.CloseMicrophoneConnect,
                rightButtonOnTap: () {
                  onTap();
                },
              );
            },
          )
        ],
      );
    }
    return GestureDetector(
      child: Container(
        height: 48.w,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "开放鉴宝申请",
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.white,
              ),
            ),
          ],
        ),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8.w), color: Color(0xFFF04529)),
        margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 5.w),
      ),
      onTap: () async {
        onTap();
      },
    );
  }

  onTap() async {
    if (isConnect) {
      int index_where =
          data.indexWhere((element) => element['connect_at'] != null);
      if (index_where != -1) {
        DialogUtil.showMyDialog(
            dialogType: DialogType.DisconnectWithUserConnect);
      } else {
        management();
      }
    } else {
      management();
    }
  }

  management() async {
    await HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/studios/${StreamConf.liveId}/interaction',
      method: HttpUtil.MethodPut,
    ).then((value) async {
      if (value.statusCode == 200) {
        CustomToast.show(value.data['msg'] ?? "");
        if ((value.data['msg'] ?? "").toString().indexOf('开启') != -1) {
          setState(() {
            isConnect = true;
          });
        } else {
          setState(() {
            isConnect = false;
          });
        }
        if (widget.callBack != null) {
          widget.callBack!(isConnect);
        }
        await RongUtil.operation(OperationKey.interaction, {
          "is_interaction": isConnect,
        });
      }
    });
  }
}
